import React, { useState } from 'react';
import {
  IonContent,
  IonHeader,
  IonPage,
  IonTitle,
  IonToolbar,
  IonButtons,
  IonButton,
  IonIcon,
  IonFooter,
  IonList,
} from '@ionic/react';
import { volumeHigh, volumeMute, settings } from 'ionicons/icons';
import ChatMessage from '../components/chat/ChatMessage';
import ChatInput from '../components/chat/ChatInput';
import { useChatStore } from '../store/chat';

const ChatPage: React.FC = () => {
  const { sendMessage, histories, currentService, isLoading } = useChatStore();
  const [isSpeakerOn, setIsSpeakerOn] = useState(false);
  const messages = histories[currentService] || [];

  const handleSend = async (text: string) => {
    if (text.trim()) {
      await sendMessage(text, "你是一个专业的AI助手，请用简洁、专业的方式回答用户的问题。");
    }
  };

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>AI助手</IonTitle>
          <IonButtons slot="end">
            <IonButton onClick={() => setIsSpeakerOn(!isSpeakerOn)}>
              <IonIcon icon={isSpeakerOn ? volumeHigh : volumeMute} />
            </IonButton>
            <IonButton routerLink="/chat/settings">
              <IonIcon icon={settings} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
      </IonHeader>

      <IonContent>
        <IonList>
          {messages.map((message) => (
            <ChatMessage
              key={message.id}
              text={message.text}
              isBot={message.isBot}
              isSpeakerOn={isSpeakerOn}
            />
          ))}
          {isLoading && (
            <div className="ion-text-center ion-padding">
              <p>正在思考...</p>
            </div>
          )}
        </IonList>
      </IonContent>

      <IonFooter>
        <ChatInput onSend={handleSend} isLoading={isLoading} />
      </IonFooter>
    </IonPage>
  );
};

export default ChatPage;